﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Ioc;
using ICSharpCode.AvalonEdit.Rendering;
using JiveMessenger.CustomControls;
using JiveMessenger.AvalonEdit;
using JiveMessenger.Models;
using System.Linq;
using JmShared;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Threading;
using System.Windows.Media;
using System.IO;
using System.Xml;
using System.Windows.Threading;
using System.Windows.Input;
using System.Diagnostics;
using System.Collections.Specialized;
using JiveMessenger.User;
using JariZ;
using System.Windows;
using System.Text.RegularExpressions;
using JiveMessenger.Utilities;
using System.Security;

namespace JiveMessenger.ViewModels
{
    public class ViewModelLoginControl : ViewModelBase, IViewModelLoginControl
    {
        private IClient _currentClient;

        private object LockObject = new object();


        public RelayCommand LoginCommand { get; private set; }
        public RelayCommand ResetPasswordCommand { get; private set; }
        public RelayCommand RegisterUserCommand { get; private set; }



        private string _username;
        public string Username
        {
            get { return _username; }
            set
            {
                if (_username != value)
                {
                    Set(() => Username, ref _username, value);
                }
            }
        }


        private SecureString _password;
        public SecureString Password
        {
            get { return _password; }
            set
            {
                if (_password != value)
                {
                    Set(() => Password, ref _password, value);
                }
            }
        }


        private string _loginControlStatusText;
        public string LoginControlStatusText
        {
            get { return _loginControlStatusText; }
            set
            {
                if (_loginControlStatusText != value)
                {
                    Set(() => LoginControlStatusText, ref _loginControlStatusText, value);
                }
            }
        }

        private bool _isLoginButtonEnabled;
        public bool IsLoginButtonEnabled
        {
            get { return _isLoginButtonEnabled; }
            set
            {
                if (_isLoginButtonEnabled != value)
                {
                    Set(() => IsLoginButtonEnabled, ref _isLoginButtonEnabled, value);
                }
            }
        }

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public ViewModelLoginControl(IClient currentClient)
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
                this.Password = new SecureString();
            }
            else
            {
                _currentClient = currentClient;
                this.Username = Properties.Settings.Default.Username;
                this.Password = StaticMethods.DecryptString(Properties.Settings.Default.Password);
               
                IsLoginButtonEnabled = true;

                RegisterUserCommand = new RelayCommand(RegisterUserCommandAction);
                ResetPasswordCommand = new RelayCommand(ResetPasswordCommandAction);
                LoginCommand = new RelayCommand(LoginCommandAction);//, () => IsLoginButtonEnabled);
               // LoginCommand.DependsOn(() => IsLoginButtonEnabled);
             //   LoginCommand.DependsOn(() => _currentClient.IsLoggedIn);

                if (!Properties.Settings.Default.RememberMyPassword)
                    Properties.Settings.Default.Password = "";
                if (!Properties.Settings.Default.RememberMe)
                    Properties.Settings.Default.Username = "";

            }
            Messenger.Default.Register<NotificationMessage<string>>(this,msg =>
                {
                    switch (msg.Notification)
                    {
                        case "SetLoginStatusText":
                            {
                                this.LoginControlStatusText = msg.Content;
                                break;
                            }
                    }
                });

        }

        private void LoginCommandAction()
        {
            Match m = Regex.Match(Username, @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
            if (m.Success)
            {
                if (Password.ToString() != Properties.Settings.Default.Password)
                    Properties.Settings.Default.Password = StaticMethods.EncryptString(Password);// StaticMethods.EncryptString(Password);//StaticMethods.EncodePassword(Password.ToString());

                Properties.Settings.Default.Username = Username;
                _currentClient.StopReconnectTask();
                _currentClient.IsUserConnecting = true;
                _currentClient.StartConnectTask(false);

            }
            else
            {
                this.LoginControlStatusText = "Your Email Address is invalid";
                IsLoginButtonEnabled= true;
            }
        }
        private void ResetPasswordCommandAction()
        {
            try
            {
                Messenger.Default.Send(new NotificationMessage(this, "OpenResetPasswordWindow"));
            }
            catch (Exception err)
            {
                Messenger.Default.Send(String.Format("Error opening url. \n {0})", err.Message));
            }
        }

        private void RegisterUserCommandAction()
        {
            try
            {
                Messenger.Default.Send(new NotificationMessage(this, "OpenRegisterWindow"));
            }
            catch (Exception err)
            {
                Messenger.Default.Send(String.Format("Error opening url. \n {0})", err.Message));
            }
        }

        public override void Cleanup()
        {
            base.Cleanup();
        }

        public void RunOnNetworkConnect()
        {
            this.IsLoginButtonEnabled = true;
            this.LoginControlStatusText = string.Empty;
            _currentClient.StopReconnectRetrying = false;
        }


        public void RunOnNetworkDisconnect()
        {
            this.IsLoginButtonEnabled = true;
        }
    }
}